package com.shinhye.elephantsafe;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;

public abstract class GuardSetupBaseActivity extends Activity {
	private GestureDetector detector;
	private AlertDialog dialog;
	private SharedPreferences sp;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		sp = getSharedPreferences("Setting", MODE_PRIVATE);
		
		detector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener(){
			@Override
			public boolean onFling(MotionEvent e1, MotionEvent e2,
					float velocityX, float velocityY) {
				if(Math.abs(velocityX) < 100) {
					System.out.println("滑的好慢啊！");
					return true;
				}
				if(Math.abs(e2.getRawY() - e1.getRawY()) > 100) {
					System.out.println("要直着从左往右滑哦");
					return true;
				}
				
				if((e2.getRawX() - e1.getRawX()) > 200) {
					showPrev();
				} else if((e1.getRawX() - e2.getRawX()) > 200) {
					showNext();
				}
				return super.onFling(e1, e2, velocityX, velocityY);
			}
		});
		
	}
	
	/**
	 * Show the previous activity. 
	 */
	public abstract void showNext();
	
	/**
	 * Show the next activity. 
	 */
	public abstract void showPrev();
	
	public void next(View v) {
		showNext();
	}
	
	public void previous(View v) {
		showPrev();
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		detector.onTouchEvent(event);
		return super.onTouchEvent(event);
	}
	
	@Override
	public void onBackPressed() {
		Builder builder = new Builder(this);
		
		View view = View.inflate(this, R.layout.dialog_guide_exit, null);
		view.findViewById(R.id.guide_btn_cancel).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				return;
			}
		});
		view.findViewById(R.id.guide_btn_ok).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				SharedPreferences sp = getSharedPreferences("Setting", MODE_PRIVATE);
				Editor editor = sp.edit();
				editor.putBoolean("skipguide", true);
				editor.commit();
				
				dialog.dismiss();
				finish();
				Intent intent = new Intent(getApplicationContext(), GuardThrefActivity.class);
				startActivity(intent);
				return;
			}
		});
		
		dialog = builder.create();
		dialog.setView(view, 0, 0, 0, 0);
		dialog.show();
	}
	
	public SharedPreferences getSP() {
		return sp;
	}
}
